#!/usr/bin/python
# -*-coding:utf-8 -*-
import time
import json
import pickle
import datetime
from selenium import webdriver
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
import platform
import os
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
import logging

class MyWeiBo:
    def __init__(self):
        # 采用谷歌浏览器
        chrome_opt = Options()
        chrome_opt.add_argument('--no-sandbox')  # Bypass OS security model
        # applicable to windows os only
        chrome_opt.add_argument('--disable-gpu')
        # chrome_opt.add_argument('start-maximized')
        chrome_opt.add_argument('disable-infobars')
        chrome_opt.add_argument("--disable-extensions")
        chrome_opt.add_argument('--disable-dev-shm-usage')
        chrome_opt.add_argument('window-size=1920x1480')
        sys = platform.system()
        print(sys)
        if sys == "Windows":
            print("sys=OS is Windows!!!")
            self.cookpath="./weibo.pkl"
            path = r"D:\local\Python\tool\chromedriver.exe"
        elif sys == "Linux":
            print("sys=OS is centos!!!")
            path = r"/root/local/python/chromedriver/chromedriver"
            self.cookpath="./weibo.pkl"
            chrome_opt.add_argument("--headless")
            #headless将在无头模式下启动Chrome浏览上下文

        ser = Service(path)
        self.browser = webdriver.Chrome(
            service=ser, options=chrome_opt)

    def loginWithCookies(self):
        """
        跳转微头条
        :return:
        """
        
        if os.path.exists(self.cookpath) == False:
            self.login()
        self.browser.get(
            "https://weibo.com/")
        cookies = pickle.load(open(self.cookpath, "rb"))
        for cookie in cookies:
            if 'expiry' in cookie:
                cookie['expiry'] = int(cookie['expiry'])
            self.browser.add_cookie(cookie)
        time.sleep(1)
        self.browser.refresh()

    def postWeiToutiao(self, content):
        print("postWeiToutiao begin")

        """
        今日头条：格言提醒
        """
        # load
        self.browser.get(
            "https://weibo.com/")
        time.sleep(3)
        # 微头条内容框
        # presence_of_element_located（locator）：判断某个元素是否存在DOM中
        weitoutiao_content = WebDriverWait(self.browser, 10).until(EC.presence_of_element_located(
            (By.CSS_SELECTOR, ".Form_input_2gtXx")))   
        # CSS选择器 https://www.w3school.com.cn/cssref/css_selectors.asp
        # https://github.com/seleniumhq/selenium/issues/1480
        # div CLASS .intro id .
        weitoutiao_content.send_keys(content)
        #https://blog.csdn.net/weixin_44065501/article/details/89314538
        weitoutiao_content.send_keys(Keys.ENTER)
        print("step1-------------")
        time.sleep(2)

        # 点击发布 
        #https://my.oschina.net/u/4273790/blog/3807807
        actions = ActionChains(self.browser)
        weitoutiao_send_btn = self.browser.find_element(By.CSS_SELECTOR,".woo-button-main.woo-button-flat.woo-button-primary.woo-button-m.woo-button-round.Tool_btn_2Eane")  # 双击按钮
        weitoutiao_send_btn.send_keys(Keys.SPACE)
        print("step2-------------")

    def login(self):
        self.browser.get("https://weibo.com/newlogin")
        time.sleep(60)
        cookies = self.browser.get_cookies()
        pickle.dump(cookies, open(self.cookpath, "wb"))
        print("dump cookies succed")

    def close(self):
        #self.browser.close()
        self.browser.quit()


 # https: // www.programcreek.com/python/example/88674/selenium.webdriver.support.expected_conditions.element_to_be_clickable
 # https://github.com/Tangnameless/WeiboSpider
if __name__ == '__main__':

    # https://www.yht7.com/news/17483
    today = datetime.date.today()
    y = datetime.datetime.now().year  # 获取年份
    m = datetime.datetime.now().month  # 获取月份
    d = datetime.datetime.now().day  # 获取“日”

    targetDay = datetime.date(y, m, d)  # 将输入的日期格式化成标准的日期
    dayCount = targetDay - \
        datetime.date(targetDay.year - 1, 4, 15)  # 减去上一年最后一天
    
    msg = "#币圈诈骗犯刘庆#  \r\n 今天是 "
  

    msg += time.strftime("%Y-%m-%d", time.localtime())
    msg += "\r\n"
    msg += "已拖欠还款"
    msg += str(dayCount.days)
    msg += "天。 \r\n"

    msg += "币圈刘庆有哪些连环诈骗手段:https://www.zhihu.com/question/515055531 \r\n"

    msg += "\r\n"
    msg += "今天第二件重要事情 "
    msg += "\r\n"
    msg += "接下来一周里可以用以下 4个步骤来应对自己强烈的欲望 "
    msg += "1 ．承认自己脑海中的欲望 ，以及渴望某种事物的感觉  "
    msg += "\r\n"
    msg += "2 ．不要马上试着转移注意力或与之争论 "
    msg += "\r\n"
    msg += "3 ．退一步考虑 ，意识到这种想法和感觉并不受你控制 ，但你可以选择是否将这些想法付诸实践  "
    msg += "\r\n"
    msg += "4 ．记住你的目标 ，提醒自己预先作出的承诺"

    weibo = MyWeiBo()

    # 判断session是否过期
    first = False
    if os.path.exists("./weibo.pkl") == False:
        print("cookies.pkl is missing")
        first = True
    if first == True :
        logging.debug("first login")
        weibo.login()
        weibo.loginWithCookies()
        weibo.postWeiToutiao(msg)
        weibo.close()
    else:
        try :
            weibo.loginWithCookies()
            weibo.postWeiToutiao(msg)
        finally:
            weibo.close()
            print(msg)


##https://blog.csdn.net/u012587637/article/details/47979531